<template>
  <BasicModal
    v-bind="$attrs"
    :title="isUpdate ? '编辑用户组' : '新增用户组'"
    :width="600"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm
      @register="registerForm"
      :model="formData"
      :schemas="schemas"
      :showActionButtonGroup="false"
    />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { message } from 'ant-design-vue';
  import { addUserGroup, editUserGroup } from '@/api/demo/device';
  import { schemas } from './account.data';

  const emit = defineEmits(['success']);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    console.log(data);
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const isUpdate = ref(false);
  const formData = reactive<Recordable>({});

  const [registerForm, { validateFields, setFieldsValue, resetFields, updateSchema }] = useForm({
    schemas,
    showActionButtonGroup: false,
  });

  // 监听模态框参数变化

  // 提交表单
  async function handleSubmit() {
    try {
      console.log('====================================');
      console.log(validateFields);
      console.log('====================================');
      const values = await validateFields();
      console.log('====================================');
      console.log(values);
      console.log('====================================');
      let response;

      if (isUpdate.value) {
        // 编辑用户组 - 直接使用表单中的id值
        response = await editUserGroup(values);
      } else {
        // 新增用户组
        response = await addUserGroup(values);
      }

      if (response.code === 200) {
        message.success(isUpdate.value ? '编辑成功' : '新增成功');
        closeModal();
        emit('success', { isUpdate: isUpdate.value, values });
      } else {
        message.error(response.msg || (isUpdate.value ? '编辑失败' : '新增失败'));
      }
    } catch (error) {
      // 表单验证失败
    }
  }
</script>
